package com.test.latitudex;

import java.util.Locale;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Looper;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.test.latitudex.utilities.InvitationsListAdapter;
import com.test.latitudex.utilities.LocationBroadcastReceiver;
import com.test.latitudex.utilities.RegistrationManager;

/**
 * A dummy fragment representing a section of the app, but that simply displays dummy text.
 */
public class InvitationsFragment extends android.support.v4.app.Fragment {
	/**
	 * The fragment argument representing the section number for this fragment.
	 */
	public static final String ARG_SECTION_NUMBER = "section_number";
	@SuppressWarnings("unused")
	private static final String LOG_TAG = "FriendsActivity";
	int minTime, minDist;

	static String interval = null, duration = null, id = null;
	static Button btn1;
	static Button btn2;
	static Button btn3;
	static EditText et1;
	static EditText et2;
	static EditText et3;
	static TextView tv1;
	static String userId;
	static LocationBroadcastReceiver brc;
	static Context ctx;
	static Activity act;
	static String lastUpdate = null;
	static boolean serviceStarted = false;
	static ListView list;
	static InvitationsListAdapter adapter;
	static ProgressDialog progDialog;

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		ctx = this.getActivity();
		act = this.getActivity();
		list = (ListView) (getView().findViewById(R.id.invitationsList));
		btn1 = (Button) (getView().findViewById(R.id.sendInvitationButton));
		
		btn1.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				DialogFragment newFragment = new SendInvitationDialogFragment();
				newFragment.show(getActivity().getSupportFragmentManager(), "SendInvitation");
			}
			
		});
		
		adapter = new InvitationsListAdapter(this.getActivity());
		list.setAdapter(adapter);

		list.setLongClickable(true);
		list.setOnItemLongClickListener(new OnItemLongClickListener() {
			public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id) {
				return true;
			}
		});

		list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				
			}

		});

		
		
	}

		
	public static class SendInvitationDialogFragment extends DialogFragment {
		
		@Override
		public Dialog onCreateDialog(Bundle savedInstanceState) {
			AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		    // Get the layout inflater
		    LayoutInflater inflater = getActivity().getLayoutInflater();

		    // Inflate and set the layout for the dialog
		    // Pass null as the parent view because its going in the dialog layout
		    builder.setView(inflater.inflate(R.layout.invitation_dialog_layout, null))
		    // Add action buttons
		           .setPositiveButton(R.string.sendInvitationOkButton, new DialogInterface.OnClickListener() {
		               @Override
						public void onClick(final DialogInterface dialog, int id) {
							synchronized (this) {
								new Thread(new Runnable() {

									@Override
									public void run() {
										Looper.prepare();
										EditText et = (EditText) Dialog.class.cast(dialog).findViewById(
												R.id.inviteeEmail);
										try {
											RegistrationManager.getEntity().sendInvitation(
													et.getText().toString().toLowerCase(Locale.ENGLISH));
										} catch (Exception e) {
											getActivity().runOnUiThread(new Runnable() {

												@Override
												public void run() {
													Toast.makeText(
															getActivity(),
															"Network communication unsuccesful. Please check network connection!",
															Toast.LENGTH_LONG).show();
												}

											});
										}
										refreshInviteList();
									}

								}).start();

							}
						}
					})
		           .setNegativeButton(R.string.sendInvitationCancelButton, new DialogInterface.OnClickListener() {
		               public void onClick(DialogInterface dialog, int id) {
		                  
		               }
		           });      
		    return builder.create();
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.invitations_activity_layout, container, false);
		return rootView;
	}

	public static void deleteInvitationFromList(int position) {
			RegistrationManager.getEntity().getInvitationData().remove(position);
			((Activity) ctx).runOnUiThread(new Runnable() {

				@Override
				public void run() {
					adapter = new InvitationsListAdapter(act);
					list = (ListView) (act.findViewById(R.id.invitationsList));
					list.setAdapter(adapter);
					list.invalidate();
				}

			});
	}
	
	public static void refreshInviteList() {
		try {
			if(RegistrationManager.getEntity().downloadInvitations()){
				((Activity) ctx).runOnUiThread(new Runnable() {

					@Override
					public void run() {
						adapter = new InvitationsListAdapter(act);
						list = (ListView) (act.findViewById(R.id.invitationsList));
						if(list != null){
							list.setAdapter(adapter);
							list.invalidate();
						}
					}

				});
			}
		} catch (Exception e) {
			((Activity) ctx).runOnUiThread(new Runnable() {

				@Override
				public void run() {
					Toast.makeText(ctx, "Network unreachable. Please try later.", Toast.LENGTH_SHORT).show();
				}

			});
		}
		
}
	

}